package com.salim.leetcode.$82;


public class RemoveDuplicatesFromSortedListII {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode result = null;
        if(head==null){
            return result;
        }
        if(head.next==null){
            return head;
        }
        ListNode prev = new ListNode();
        prev.next = null;
        boolean dupl = false;
        while (head.next!=null){
            if(head.val==head.next.val){
                dupl = true;
                head = head.next;
                prev.next = null;
            }else{
                if(dupl){
                    prev.next = head.next;
                    head = prev.next;
                    dupl = false;
                }else{
                    if(result==null){
                        result = head;
                    }
                    prev.next = head;
                    prev = prev.next;
                    head = head.next;
                }
            }
        }
        if(result==null){
            result = prev.next;
        }
        return result;
    }

    public class ListNode {
       int val;
       ListNode next;
       ListNode() {}
       ListNode(int val) { this.val = val; }
       ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
